<template>
  <div>
    <el-row class="demo-autocomplete">
      <el-select v-model="select.sid" filterable placeholder="学科" @change="change" style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
          <el-option v-for="(item,index) in select.classAll" :key="index" :value="item.sid" :label="item.subName"></el-option>
      </el-select>
      <el-select v-model="select.pointname" filterable placeholder="知识点" style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
          <el-option v-for="(item,index) in select.points" :key="index" :value="item.point" :label="item.point"></el-option>
      </el-select>
      <el-button type="primary" @click="searchTable">查找</el-button>
      <el-button type="danger" @click="resetTable">重置</el-button>
    </el-row>
   <el-table  :data="tableData" max-height="520px" style="width: 100%;height:80%" :row-class-name="tableRowClassName">
    <el-table-column type="expand">
    </el-table-column>
    <el-table-column
      prop="createTime"
      label="创建日期"
      sortable
      width="180"
      column-key="date"
      :filters="table.createTimeArr"
      :filter-method="filterHandler"
    >
    </el-table-column>
    <el-table-column
      prop="paperName"
      label="试卷名称"
      width="250"
      :filters="table.paperNameArr"
      :filter-method="filterHandler"
      >
    </el-table-column>
    <el-table-column
      prop="subName"
      label="学科"
      width="250"
      :filters="table.subNameArr"
      :filter-method="filterHandler"
      >
    </el-table-column>
    <el-table-column
      prop="points"
      label="知识点"
      :filters="table.pointsArr"
      :filter-method="filterHandler">
      <template slot-scope="scope">
        <el-tag
          :type="'success'" v-for="(item,index) in scope.row.points.split(':').length" :key="index"
          disable-transitions>{{scope.row.points.split(':')[index]}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="300">
      <template slot-scope="scope">
        <el-button
          size="mini"
          type="primary"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="success"
          @click="handleView(scope.$index, scope.row)">预览</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        <el-button
          size="mini"
          type="warning"
          @click="handleTest(scope.$index, scope.row)">考试</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination background layout="prev, pager, next"  @current-change="handleCurrentChange" :page-size="pagination.pageSize" :total="pagination.total"></el-pagination>

      <el-dialog
        title="发布考试"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
    <el-form ref="form" :model="sizeForm" label-width="80px" size="mini">
    <el-form-item label="考试名称">
       <el-input v-model="sizeForm.examName"></el-input>
    </el-form-item>
    <el-form-item label="考试地址">
       <el-input v-model="sizeForm.examAddress"></el-input>
    </el-form-item>
    <el-form-item label="开始时间">
      <!-- "sizeForm.endTime" -->
      <div class="block">
          <el-date-picker
            v-model="sizeForm.startTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </div>
    </el-form-item>
    <el-form-item label="结束时间">
      <div class="block">
          <el-date-picker
            v-model="sizeForm.endTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </div>
    </el-form-item>
  <el-form-item label="考试班级" prop="point">
        <el-select v-model="sizeForm.classId" multiple placeholder="请选择">
          <el-option v-for="(item,index) in Class" :key="index" :label="item.cname" :value="item.cid"></el-option>
        </el-select>
  </el-form-item>
</el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editTest">确 定</el-button>
        </span>
      </el-dialog>

  </div>
</template>

<script>
import axios from 'axios'
import {getCourse, getKnowledge} from "../../api/data";
  export default {
    name:'paperMessage',
    data() {
      return {
        Class:[],
        dialogVisible: false,
        sizeForm: {
          examName: '',
          examAddress:'',
          startTime:'',
          endTime:'',
          classId:[],
          examPaperCode:'',//试卷id
        },
        select:{//用来存储下拉框相关数据
          classAll:[],//获取所有课程信息
          sid:'',//收集
          classname:'',
          point:'',//收集
          pointname:'',
          points:'',//获取所有知识点信息
        },
        table:{  //保存所有的信息以供筛选
          createTimeArr:[],
          paperNameArr:[],
          subNameArr:[],
          pointsArr:[],//保存所有试卷的（去重）
        },//存储表格的相关数据
        pagination:{//用来存储分页的相关数据
          total:88,//总数量
          pageSize:8,//每一页的数量
        },
        tableData:[],//用来展示每一次数据
        tableDataShow:[],//用来保存所有数据
        tableDataAll: []
      }
    },
    mounted() {
     getCourse().then(res => {
      this.select.classAll = res.data;
    })
      axios.get(`http://42.193.219.14:8080/getExamPaperInformation`,{
        headers: {"Authorization": "Bearer "+ sessionStorage.getItem('token')}
      }).then(
      response => {
        console.log('请求成功了', response.data.data);
        this.tableDataAll=response.data.data||[];
        this.tableData=this.tableDataAll.slice(0,8);//挂载完毕表格渲染
        this.tableDataAll.forEach(element => {
            var flag1=0,flag2=0,flag3=0,flag4=0;
          this.table.createTimeArr.forEach(el=>{
              if(el.text===element.createTime){
                flag1=1;
              }
          })
            if(flag1===0) {
            this.table.createTimeArr.push(
            {
              text:`${element.createTime}`,
              value:`${element.createTime}`
            });
          }
        this.table.paperNameArr.forEach(el=>{
              if(el.text===element.paperName){
                flag2=1;
              }
          })
            if(flag2===0) {
            this.table.paperNameArr.push(
            {
              text:`${element.paperName}`,
              value:`${element.paperName}`
            });
          }
        this.table.subNameArr.forEach(el=>{
              if(el.text===element.subName){
                flag3=1;
              }
          })
            if(flag3===0) {
            this.table.subNameArr.push(
            {
              text:`${element.subName}`,
              value:`${element.subName}`
            });
          }
          var elsplit=element.points.split(':');
          for(var i=0;i<elsplit.length;i++){
            var flag5=0;
            // 如果拆分之后不存在，直接插入
            this.table.pointsArr.forEach(el=>{
            if(el.text===elsplit[i]){
              flag5=1;
            }
          })
          if(flag5===0)
          {
              this.table.pointsArr.push({
                text:elsplit[i],
                value:elsplit[i]});
            }
          }
        })
      },
      error => {
        console.log('请求失败', error.message);
      }
    );
    },

    methods: {
      tableRowClassName({rowIndex}) {
        if (rowIndex %2=== 1) {
          return 'warning-row';
        } else{
          return 'success-row';
        }
      },

      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },

      change() {
      console.log('下拉框状态改变');
      axios.get(`http://42.193.219.14:8080/getKnowledgePointsBySid`, {
        headers: {"Authorization": "Bearer "+ sessionStorage.getItem('token')},
        params: {
          sid: this.select.sid//传递课程号参数
        }
      }).then(
        response => {
          console.log('知识点请求成功了', response.data.data);
          this.select.points = response.data.data;
          //获取课程名用于搜索展示
          this.select.classAll.forEach(element => {
            if(this.select.sid===element.sid){
              this.select.classname=element.subName
            }
          });
        },
        error => {
          console.log('知识点请求失败', error.message);
        }
      )
    },
     formatDate(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
          m = m < 10 ? ('0' + m) : m;
          var d = date.getDate();
          d = d < 10 ? ('0' + d) : d;
          var h = date.getHours();
          h=h < 10 ? ('0' + h) : h;
          var minute = date.getMinutes();
          minute = minute < 10 ? ('0' + minute) : minute;
          var second=date.getSeconds();
          second=second < 10 ? ('0' + second) : second;
          return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    },
    editTest(){
      this.sizeForm.startTime=this.formatDate(this.sizeForm.startTime);
      this.sizeForm.endTime=this.formatDate(this.sizeForm.endTime)
      axios({
        method: "post",
        url: "http://42.193.219.14:8080/publishExam",
        headers: {
          "Authorization": "Bearer "+ sessionStorage.getItem('token'),
          "Content-Type": "application/json"
        },
        withCredentials: true,
        data: this.sizeForm
      }).then((response) => {
        console.log(response);
      });
      this.dialogVisible=false;
    },
      handleCurrentChange(val){//页面切换，默认参数1为页码
        this.tableData=this.tableDataAll.slice((val-1)*8,val*8)
      },

      searchTable(){
        if(this.select.classname!==''&&this.select.pointname!==''){
            console.log('搜索'+this.select.classname+this.select.pointname);
            this.tableData=this.filterArr(this.tableDataAll);
        }
        else {
            this.$message({
            type: 'warning',
            message: '学科及知识点不为空'
          });
        }
      },

      resetTable(){
        this.tableData=this.tableDataAll;//重新跟新
      },

      formatter(row) {
        return row.classname;
      },

      filterHandler(value, row, column) {
        const property = column['property'];
        return row[property] === value;
      },

       handleEdit(index, row) {
        console.log(index, row);
      },

      handleDelete(index, row) {
        console.log(row);
        this.$confirm('将永久删除此试卷, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.tableData=this.filterArr2(this.tableData,row)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      handleTest(a,b){//分配考试
          this.dialogVisible=true
          this.sizeForm.examPaperCode=b.paperMessageCode;
           axios.get(`http://42.193.219.14:8080/getClassByUid`,{
             headers: {"Authorization": "Bearer "+ sessionStorage.getItem('token')}
           }).then(
            response => {
              console.log('请求成功了', response.data.data);
              this.Class = response.data.data;
            },
            error => {
              console.log('请求失败', error.message);
      }
    )
      },

      filterArr(datas,rowindex){//搜索框===数组的过滤
        return  datas.filter((data,index)=>{
          return (data.classname===this.select.classname&&data.tag===this.select.pointname);
          })
      },
      //目前都是假数据，没必要这么复杂，每套试卷都有唯一id
      filterArr2(datas,row){//删除===数组的过滤
        return  datas.filter((data,index)=>{
          return (data.classname!==row.classname||data.tag!==row.tag||data.name!==row.name||data.data!==row.data);
          })
      },
    }
  }
</script>


<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
    .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .el-select {
    margin: 10px;
  }
  .el-pagination {
    margin-left: 50%;
    margin-top: 10px;
    transform: translate(-50%);
  }
</style>
